<template>
  <!--考试-->
  <div class="exam" v-if="examDetail">
    <!--过滤栏-->
    <div class="filter-container">
      <div class="filter-item item-input">
        <el-input v-model="examInput" placeholder="请输入考试名称"></el-input>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="searchExam"><i class="el-icon-search"></i> 搜索</el-button>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="requestExam(),examInput = ''"><i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
      <div class="filter-item item-button">
        <el-button type="primary" @click="toCreateExam = true"><i class="el-icon-s-flag"></i> 创建考试</el-button>
      </div>
    </div>

    <!--考试列表-->
    <div class="exam-list">
      <el-table
          :data="examDetail.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
          border
          style="width: 100%;">
        <el-table-column
            label="序号"
            width="60"
            align="center">
          <template slot-scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
            prop="name"
            label="考试名称"
            width="200"
            align="center">
          <template slot-scope="scope">
            <el-tooltip content="查看考试详情" placement="top">
                            <span class="col2-cell-style"
                                  @click="viewExamDetail((currentPage - 1) * pageSize + scope.$index)">{{scope.row.name}}</span>
            </el-tooltip>

          </template>
        </el-table-column>
        <el-table-column
            prop="class"
            label="考试班级"
            width="180"
            align="center">
        </el-table-column>
        <el-table-column
            prop="duration"
            label="考试时长"
            width="80"
            align="center">
        </el-table-column>
        <el-table-column
            prop="startTime"
            label="开考时间"
            width="160"
            align="center">
        </el-table-column>
        <el-table-column
            prop="endTime"
            label="结束时间"
            width="160"
            align="center">
        </el-table-column>
        <el-table-column
            prop="createdTime"
            label="创建时间"
            width="160"
            align="center">
        </el-table-column>
        <el-table-column
            prop="creator"
            label="创建人"
            align="center">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="80"
            align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 0" type="success" disable-transitions>未开始</el-tag>
            <el-tooltip content="该场考试正在考试中" placement="top">
              <el-tag v-if="scope.row.status == 1" type="info" disable-transitions>考试中</el-tag>
            </el-tooltip>
            <el-tag v-if="scope.row.status == 2" type="warning" disable-transitions>已结束</el-tag>
            <el-tag v-if="scope.row.status == 3" type="danger" disable-transitions>阅卷中</el-tag>
            <el-tooltip content="该场考试已完成阅卷" placement="top">
              <el-tag v-if="scope.row.status == 4" disable-transitions>已阅卷</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                v-if="(scope.row.status == 0) || (scope.row.status == 1)"
                @click="locateCurExam((currentPage - 1) * pageSize + scope.$index)">添加考生
            </el-button>
            <el-button
                size="mini"
                type="success"
                v-if="scope.row.status == 0"
                @click="startExam((currentPage - 1) * pageSize + scope.$index)">开始
            </el-button>
            <el-button
                size="mini"
                type="danger"
                v-if="scope.row.status == 1"
                @click="endExam((currentPage - 1) * pageSize + scope.$index)">结束
            </el-button>
            <el-tooltip content="手动评阅全部有提交记录的考生答卷" placement="top">
              <el-button
                  size="mini"
                  type="primary"
                  v-if="(scope.row.status == 2) || (scope.row.status == 3)"
                  @click="reviewPapers(scope)">手动阅卷
              </el-button>
            </el-tooltip>

            <el-button
                size="mini"
                type="danger"
                v-if="scope.row.status != 1"
                @click="curExamIndex = (currentPage - 1) * pageSize + scope.$index, toDelExam = true">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <Pagination :currentPage="currentPage" :pageSize="pageSize" :total="examDetail.length"
                :handleSizeChange="handleSizeChange" :handleCurrentChange="handleCurrentChange"></Pagination>

    <!--创建考试 对话框-->
    <el-dialog title="创建考试" :visible.sync="toCreateExam">
      <el-form ref="examForm" :model="examForm" status-icon :rules="examRules">
        <el-form-item label="考试名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="examForm.name" autocomplete="off" placeholder="请输入考试名称"></el-input>
        </el-form-item>
        <el-form-item label="考试班级" :label-width="formLabelWidth" prop="class">
          <el-select v-model="examForm.class" filterable placeholder="试试搜索：班级名称">
            <el-option
                v-for="item in classOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试试卷" :label-width="formLabelWidth" prop="paper">
          <el-select v-model="examForm.paper" filterable placeholder="试试搜索：试卷名称">
            <el-option
                v-for="item in paperOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="考试时长" :label-width="formLabelWidth" prop="duration">
          <el-input-number v-model="examForm.duration" :min="1" :max="200" label="考试时长"></el-input-number>
        </el-form-item>
        <el-form-item label="考试时间" :label-width="formLabelWidth" prop="dateTime">
          <el-date-picker
              v-model="examForm.dateTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" :label-width="formLabelWidth" prop="creator">
          <el-input v-model="examForm.creator" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toCreateExam = false">取 消</el-button>
        <el-button type="primary" @click="createExam()">保 存</el-button>
      </div>
    </el-dialog>

    <!--添加考生 对话框-->
    <el-dialog title="添加考生" :visible.sync="toAddExaminee">
      <div slot="title" class="header-title">
        <span>添加考生：{{ examTitle }}</span>
      </div>

      <el-form ref="examineeForm" :model="examineeForm" status-icon :rules="examineeRules">
        <el-form-item label="考生号" :label-width="formLabelWidth" prop="id">
          <el-input v-model="examineeForm.id" autocomplete="off" clearable
                    placeholder="请输入考生号，多个以英文逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="考生姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="examineeForm.name" autocomplete="off" clearable
                    placeholder="请输入学生姓名，多个以英文逗号分隔"></el-input>
        </el-form-item>
        <el-form-item label="身份证信息" :label-width="formLabelWidth" prop="IDcard">
          <el-input v-model="examineeForm.IDcard" autocomplete="off" clearable
                    placeholder="请输入身份证号码，多个以英文逗号分隔"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toAddExaminee = false">取 消</el-button>
        <el-button type="primary" @click="addExaminee">保 存</el-button>
      </div>
    </el-dialog>

    <!--查看考试详情 对话框-->
    <el-dialog title="查看考试详情" :visible.sync="toViewExamDetail" fullscreen v-if="toViewExamDetail">
      <div slot="title" class="header-title">
        <span>{{ examTitle }}</span>
        &nbsp;
        &nbsp;
        &nbsp;
        &nbsp;
        <el-progress type="circle" class="filter-item"
                     :percentage="alreadySubmitCandidateCount/totalCandidateCount * 100"
                     :width="60" color="#67C23A" :show-text="false"></el-progress >
        &nbsp;
        &nbsp;
        <span class="filter-item">{{alreadySubmitCandidateCount}} (已交) / {{totalCandidateCount}} (总人数)</span>
      </div>

      <!--过滤栏-->
      <div class="filter-bar">
        <el-input
            placeholder="请输入考生号搜索"
            v-model="eidInput"
            clearable
            class="filter-item">
        </el-input>
        <el-button type="primary" class="filter-item" @click="searchExaminee(curExamIndex)"><i
            class="el-icon-search "></i> 搜索
        </el-button>
        <el-button type="primary" class="filter-item item-margin-left-16" @click="viewExamDetail(curExamIndex)">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
        <!--<el-button type="primary" class="filter-item item-margin-left-16" @click="take_up(curExamIndex)"><i-->
        <!--class="el-icon-upload"></i> 收卷-->
        <!--</el-button>-->
        <!--                <a href="'http://localhost:8080/userExcel?exam_id='+examDetail[curExamIndex].examId" style="text-decoration:none">-->
        <el-tooltip content="下载本场考试所有考生的成绩汇总表" placement="top">
          <el-button type="primary" class="filter-item item-margin-left-16" @click="downloadExcel">
            <i class="el-icon-document"></i> 下载成绩
          </el-button>
        </el-tooltip>
        <!--                </a>-->
        <!--<el-tooltip content="下载本场考试考生提交的代码" placement="top">-->
        <!--  <el-button type="primary" class="filter-item item-margin-left-16" @click="downloadZip">-->
        <!--    <i class="el-icon-receiving"></i> 下载答卷-->
        <!--  </el-button>-->
        <!--</el-tooltip>-->
        <el-button type="primary" class="filter-item item-margin-left-16" @click="viewOriginPaper">
          <i class="el-icon-view"></i> 查看原卷
        </el-button>
        <el-tooltip content="系统将自动为考生答卷评分" placement="top">
          <el-button type="primary" class="filter-item item-margin-left-16" @click="gradeAll">
            <i class="el-icon-position"></i> 一键阅卷
          </el-button>
        </el-tooltip>
        <el-tooltip content="下载本场考试所有考生提交各题目时间差值的汇总表" placement="top">
          <el-button type="primary" class="filter-item item-margin-left-16" @click="gradeCheck">
            <i class="el-icon-camera-solid"></i> 作弊检测
          </el-button>
        </el-tooltip>
        <el-tooltip content="下载本场考试的重复率检测报告" placement="top">
          <el-button type="primary" class="filter-item item-margin-left-16" @click="downloadRepCheckReport">
            <i class="el-icon-s-opportunity"></i> 查重报告
          </el-button>
        </el-tooltip>
        <el-button type="primary" class="filter-item item-margin-left-16" @click="toViewExamDetail = false">
          <i class="el-icon-circle-close"></i> 关闭页面
        </el-button>
      </div>

      <!--考生表格-->
      <el-table
          @sort-change="changeCandidateTableSort"
          v-loading.fullscreen.lock="loading"
          element-loading-text="阅卷中，请勿刷新或跳转到其他页面，耗时可能较长，请耐心等待"
          :data="examDetail[curExamIndex].examineeData.slice((stuCurPage - 1) * stuPageSize, stuCurPage * stuPageSize)"
          border
          style="width: 100%"
          id="exportExcel">
        <el-table-column
            label="序号"
            width="80"
            align="center">
          <template slot-scope="scope">
            {{scope.$index + 1}}
          </template>
        </el-table-column>
        <el-table-column
            label="考生号"
            prop="id"
            :sortable="'custom'"
            width="180"
            align="center">
        </el-table-column>
        <el-table-column
            label="姓名"
            prop="name"
            width="160"
            align="center">
          <template slot-scope="scope">
            <el-tooltip content="查看考生答卷和修改评分" placement="top">
                            <span class="col2-cell-style"
                                  @click="reviewStuPaper((stuCurPage - 1) * stuPageSize + scope.$index)">{{scope.row.name}}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
            label="成绩"
            prop="grade"
            :sortable="'custom'"
            width="80"
            align="center">
        </el-table-column>
        <el-table-column
            label="所属班级"
            prop="nClass"
            width="200"
            align="center">
        </el-table-column>
        <el-table-column
            label="登录IP"
            prop="loginIP"
            width="150"
            align="center">
        </el-table-column>
        <el-table-column
            label="进入时间"
            prop="enterTime"
            width="160"
            align="center">
        </el-table-column>
        <el-table-column
            label="提交时间"
            prop="submitTime"
            width="160"
            align="center">
        </el-table-column>
        <el-table-column
            label="用时(分)"
            prop="usedTime"
            :sortable="'custom'"
            width="80"
            align="center">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            align="center">
          <template slot-scope="scope">
            <el-tooltip content="学生还没有进入考试" placement="top">
              <el-tag v-if="scope.row.status == 0" type="danger" disable-transitions>未开始</el-tag>
            </el-tooltip>
            <el-tooltip content="学生进入了考试，但是没有提交试卷" placement="top">
              <el-tag v-if="scope.row.status == 1" type="info" disable-transitions>未提交</el-tag>
            </el-tooltip>
            <el-tag v-if="scope.row.status == 2" type="warning" disable-transitions>未评分</el-tag>
            <el-tag v-if="scope.row.status == 3" disable-transitions>已评分</el-tag>
            <el-tooltip content="学生答卷由教师检查和重新评分" placement="top">
              <el-tag v-if="scope.row.status == 4" type="success" disable-transitions>已审阅</el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                v-if="((scope.row.status == 1) || (scope.row.status == 2))&& examDetail[curExamIndex].status <= 1">
              重置考试
            </el-button>
            <el-button
                size="mini"
                type="danger"
                v-if="examDetail[curExamIndex].status <= 1 "
                @click="deleteExaminee((stuCurPage - 1) * stuPageSize + scope.$index)">删除
            </el-button>
            <el-button
                size="mini"
                type="info"
                v-if="scope.row.status >= 3"
                @click="reviewStuPaper((stuCurPage - 1) * stuPageSize + scope.$index)">重新阅卷
            </el-button>
          </template>
        </el-table-column>
      </el-table>


      <!--分页-->
      <Pagination :currentPage="stuCurPage" :pageSize="stuPageSize"
                  :total="examDetail[curExamIndex].examineeData.length" :handleSizeChange="handleSizeChange2"
                  :handleCurrentChange="handleCurrentChange2"></Pagination>

    </el-dialog>

    <!--查阅考生试卷 对话框-->
    <el-dialog title="" :visible.sync="toReviewStuPaper" top="2vh" width="80%" v-if="toReviewStuPaper">
      <div class="stu-paper-container">
        <div class="stu-paper-header">
          <!--                    <h1>湘潭大学_____年计算机专业上机考试</h1>-->
          <h1>{{examTitle}}</h1>
          <el-row :gutter="0">
            <el-col :span="5">
              <h3>考试总分：{{examDetail[curExamIndex].total}}</h3>
            </el-col>
            <el-col :span="5">
              <h3>出卷人：{{examDetail[curExamIndex].creator}}</h3>
            </el-col>
            <el-col :span="5">
              <h3>考生号：{{examDetail[curExamIndex].examineeData[curStuIndex].id}}</h3>
            </el-col>
            <el-col :span="5">
              <h3>姓名：{{examDetail[curExamIndex].examineeData[curStuIndex].name}}</h3>
            </el-col>
            <el-col :span="4">
              <h3>得分：{{examDetail[curExamIndex].examineeData[curStuIndex].grade}}</h3>
            </el-col>
          </el-row>
        </div>
        <div class="stu-paper-content"
             v-for="(item,index) in stuPaper">
          <h2>第 {{index + 1}} 题
            <el-input-number style="float: right" size="mini" v-model="stuPaper[index].score" :min="0"
                             :max="100" label="分数"
                             :disabled="stuPaper[index].answer == null"></el-input-number>
          </h2>
          <h4 style="clear: both">【题目描述】</h4>
          <p v-html="stuPaper[index].problem_description"></p>
          <h4>【学生答案】</h4>
          <div class="stu-answer" v-highlight>
                        <pre>
                            <code :class="stuPaper[index].language">{{stuPaper[index].answer}}</code>
                        </pre>
            <!--<div :class="stuPaper[index].language" v-html="stuPaper[index].answer"></div>-->
          </div>
        </div>
        <div class="stu-paper-footer">
          <el-button v-if="examDetail[curExamIndex].examineeData[curStuIndex].status >= 3"
                     @click="toReviewStuPaper = false">取 消
          </el-button>
          <el-button v-if="examDetail[curExamIndex].examineeData[curStuIndex].status >= 3"
                     type="primary"
                     @click="uploadScore(stuPaper, examDetail[curExamIndex].examineeData[curStuIndex].id, 0)">
            提交分数
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!--评阅本场考试中所有提交代码的考生的试卷 对话框-->
    <!--加个判断，确保 examPapers[curExamIndex] 存在，避免 undefined-->
    <el-dialog title="" :visible.sync="toReviewPapers" top="2vh" width="80%"
               v-if="toReviewPapers && examPapers[curPaper]">
      <div class="stu-paper-container">
        <div class="stu-paper-header">
          <!--                    <h1>湘潭大学_____年计算机专业上机考试</h1>-->
          <h1>{{examDetail[curExamIndex].name}}</h1>
          <el-row :gutter="0">
            <el-col :span="5">
              <h3>考试总分：{{examDetail[curExamIndex].total}}</h3>
            </el-col>
            <el-col :span="5">
              <h3>出卷人：{{examDetail[curExamIndex].creator}}</h3>
            </el-col>
            <el-col :span="5">
              <h3>考生号：{{examPapers[curPaper][0].user_id}}</h3>
            </el-col>
            <el-col :span="5">
              <h3>姓名：{{examPapers[curPaper][0].user_name}}</h3>
            </el-col>
            <el-col :span="4">
              <h3>得分：{{computeTotalScore(examPapers[curPaper])}}</h3>
            </el-col>
          </el-row>
        </div>
        <div class="stu-paper-content"
             v-for="(item,index) in examPapers[curPaper]">
          <h2>第 {{index + 1}} 题
            <el-input-number style="float: right" size="mini" :min="0" :max="100" label="分数"
                             v-model="computedScore"
                             :disabled="examPapers[curPaper][index].answer == null"></el-input-number>
          </h2>
          <h4 style="clear: both">【题目描述】</h4>
          <p v-html="handleProblemDescription(examPapers[curPaper][index].problem_description)"></p>
          <h4>【学生答案】</h4>
          <div class="stu-answer" v-highlight>
            <pre>{{examPapers[curPaper][index].answer}}</pre>
            <!--<div :class="examPapers[curPaper][index].language" v-html="examPapers[curPaper][index].answer"></div>-->
          </div>
        </div>
        <div class="stu-paper-footer">
          <el-button @click="toReviewPapers = false">取 消</el-button>
          <el-button type="primary"
                     @click="uploadScore(examPapers[curPaper], examPapers[curPaper][0].user_id, 1)">提交分数
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!--查看原卷 对话框-->
    <el-dialog title="查看原卷" :visible.sync="toViewOriginPaper" top="2vh" width="80%" v-if="originPaper.length != 0">
      <div class="paper-container">
        <div class="paper-header">
          <!--                    <h1>湘潭大学_____年计算机专业上机考试</h1>-->
          <h1>{{originPaper[0].paper_title}}</h1>
        </div>

        <div class="paper-info">
          <h3>考试总分：{{originPaper[0].paper_quest_sum * 100}}</h3>
          <h3>出卷人：{{originPaper[0].paper_creator}}</h3>
        </div>

        <!--试卷内容-->
        <div class="paper-content" v-for="(item, index) in originPaper" :key="index">
          <h2>第 {{index + 1}} 题&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{originPaper[index].problem_name}}</h2>
          <h4>【问题描述】</h4>
          <p v-html="originPaper[index].problem_description"></p>
          <h4>【输入格式】</h4>
          <p v-html="originPaper[index].problem_input_format"></p>
          <h4>【输出格式】</h4>
          <p v-html="originPaper[index].problem_output_format"></p>
          <h4>【输入样例】</h4>
          <p v-html="originPaper[index].problem_sample_input"></p>
          <h4>【输出样例】</h4>
          <p v-html="originPaper[index].problem_sample_output"></p>
          <div v-if="originPaper[index].problem_hint != null && originPaper[index].problem_hint.trim().length !== 0">
            <h4>【&nbsp;提&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;示&nbsp;】</h4>
            <p v-html="originPaper[index].problem_hint"></p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!--删除考试 对话框-->
    <el-dialog title="" :visible.sync="toDelExam" top="18vh" width="33%" center :show-close="false">
      <div class="delete-header">
        <div class="header-icon">
          <span class="icon-text">!</span>
        </div>
      </div>
      <div class="delete-tip">是否删除该考试？确认删除后将删除该考试的对应数据</div>
      <div slot="footer">
        <el-button type="primary" @click="deleteExam(curExamIndex)">确定删除</el-button>
        <el-button type="info" @click="toDelExam = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '../Pagination';
import Axios from 'axios';
import FileSaver from 'file-saver';
import XLSX from 'xlsx';
import {jsonToExcel} from "../../utils/excelUtils";

export default {
  name: "",
  data: function () {
    return {
      alreadySubmitCandidateCount: 0,
      totalCandidateCount: 1,
      timer: '',
      loading: false,
      stuPaper: [],
      originPaper: [],
      examInput: '',
      examDetail: [],
      examPapers: [],
      curPaper: 0,
      totalScore: 0,
      currentPage: 1,
      pageSize: 20,
      stuCurPage: 1,
      stuPageSize: 20,
      toCreateExam: false,
      toDelExam: false,
      examForm: {
        name: '',
        class: '',
        paper: '',
        duration: 30,
        dateTime: [],
        creator: ''
      },
      formLabelWidth: '120px',
      examRules: {
        name: [
          {required: true, message: '请输入考试名称', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
        ],
        class: [
          {required: true, message: '请选择班级', trigger: 'blur'}
        ],
        paper: [
          {required: true, message: '请选择试卷', trigger: 'blur'}
        ],
        duration: [
          {required: true, message: '考试时长不能为空', trigger: 'blur'},
          {type: 'number', message: '试考试时长必须为数字值', trigger: 'blur'}
        ],
        dateTime: [
          {required: true, message: '请选择日期', trigger: 'blur'}
        ],
        creator: [
          {required: true, message: '请输入创建人名字', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
        ]
      },
      classOptions: [{
        key: 1,
        value: '测试班级01'
      }, {
        key: 2,
        value: '测试班级02'
      }, {
        key: 3,
        value: '测试班级03'
      }],
      paperOptions: [{
        value: '828数据结构测试01'
      }, {
        value: '829数据结构测试02'
      }, {
        value: '830数据结构测试03'
      }],
      toAddExaminee: false,
      examineeForm: {
        id: '',
        name: '',
        IDcard: ''
      },
      examineeRules: {
        id: [
          {required: true, message: '学生号不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '学生姓名不能为空', trigger: 'blur'}
        ],
        IDcard: [
          {required: true, message: '身份证信息不能为空', trigger: 'blur'}
        ]

      },
      toViewExamDetail: false,
      eidInput: '', // 输入框的考生号
      toReviewStuPaper: false,
      toReviewPapers: false,
      curExamIndex: 0,
      examTitle: '',
      curStuIndex: 0,
      toViewOriginPaper: false, //是否查看原卷
      ip: '',
    }
  },
  computed: {
    computedScore: {
      get() {
        const score = this.examPapers[this.curPaper][this.index].score;
        return score == null ? 0 : score;
      },
      set(value) {
        this.examPapers[this.curPaper][this.index].score = value === 0 ? null : value;
      }
    }
  },
  components: {
    Pagination
  },
  mounted() {
    if (localStorage.getItem("token") != null) {
      this.requestExam();
      this.requestClass();
      this.requestPaper();
    } else {
      this.$router.push({path: "/login"});
    }
    this.ip = this.checkIp();
  },
  methods: {
    changeCandidateTableSort(column) {
      //获取字段名称和排序类型
      var fieldName = column.prop;
      var sortingType = column.order;

      //按照降序排序
      if(sortingType == "descending"){
        this.examDetail[this.curExamIndex].examineeData = this.examDetail[this.curExamIndex].examineeData.sort((a, b) => b[fieldName] - a[fieldName]);
      }
      //按照升序排序
      else{
        this.examDetail[this.curExamIndex].examineeData = this.examDetail[this.curExamIndex].examineeData.sort((a, b) => a[fieldName] - b[fieldName]);
      }

    },

    //存入考试
    saveExam(res) {
      this.examDetail = [];
      for (let i = 0; i < res.data.length; i++) {
        let exam = {};
        exam.total = res.data[i].total;
        exam.name = res.data[i].exam_name;
        exam.examId = res.data[i].exam_id;
        exam.class = res.data[i].class_name;
        exam.classId = res.data[i].class_id;
        exam.duration = res.data[i].duration;
        exam.startTime = this.getTime(res.data[i].start_time);
        exam.endTime = this.getTime(res.data[i].end_time);
        exam.createdTime = this.getTime(res.data[i].e_create_time);
        exam.creator = res.data[i].e_creator;
        exam.paperId = res.data[i].paper_id;
        exam.paperTitle = res.data[i].paper_title;
        exam.status = res.data[i].exam_status;
        exam.examineeData = [];
        this.examDetail.unshift(exam);
      }
      console.log("tttt===YYYYYY")
      console.log(this.examDetail)
    },
    //存入学生
    saveExaminee(res, index) {
      this.alreadySubmitCandidateCount = 0;
      this.totalCandidateCount = res.data.length == 0 ? 1 : res.data.length;
      for (let i = 0; i < res.data.length; i++) {
        let examinee = {};
        examinee.id = res.data[i].user_id + " ";
        examinee.name = res.data[i].user_name;
        examinee.nClass = res.data[i].n_class;
        examinee.grade = res.data[i].total_score;
        examinee.loginIP = res.data[i].login_ip;
        if (res.data[i].login_time != null && res.data[i].login_time != '') {
          examinee.enterTime = this.getTime(res.data[i].login_time);
        } else {
          examinee.enterTime = '';
        }
        if (res.data[i].last_submit_time != null && res.data[i].last_submit_time != '') {
          examinee.submitTime = this.getTime(res.data[i].last_submit_time);
        } else {
          examinee.submitTime = '';
        }
        examinee.status = res.data[i].user_status;
        if (res.data[i].used_time != null && res.data[i].used_time != '') {
          examinee.usedTime = res.data[i].used_time;
        } else {
          examinee.usedTime = '';
        }
        examinee.answer = ['李雷的答案01', '李雷的答案02', '李雷的答案03'];
        if(examinee.status === 2 || examinee.status === 3) {
          this.alreadySubmitCandidateCount++;
        }
        this.examDetail[index].examineeData.push(examinee);
      }
    },
    //获取考试信息
    requestExam() {
      Axios({
        method: 'post',
        url: '/admin/getCompletedExam',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          adminName: localStorage.getItem("adminName")
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        this.currentPage = 1;
        this.saveExam(res);
      }).catch((err) => {
        console.log(err);
      })

    },
    //查看原卷
    viewOriginPaper() {
      Axios({
        method: 'post',
        url: '/admin/getOriginPaper',
        data: {
          exam_id: this.examDetail[this.curExamIndex].examId,
          adminToken: localStorage.getItem("adminToken")
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].problem_description = this.handleProblemDescription(res.data[i].problem_description);
          res.data[i].problem_input_format = res.data[i].problem_input_format.replace(/\n/g, "<br>");
          res.data[i].problem_output_format = res.data[i].problem_output_format.replace(/\n/g, "<br>");
          res.data[i].problem_sample_input = res.data[i].problem_sample_input.replace(/\n/g, "<br>");
          res.data[i].problem_sample_output = res.data[i].problem_sample_output.replace(/\n/g, "<br>");
          if (res.data[i].problem_hint != null && res.data[i].problem_hint.trim().length !== 0)
            res.data[i].problem_hint = res.data[i].problem_hint.trim().replace(/\n/g, "<br>").replace(/\s/g, "&nbsp;");
        }
        this.originPaper = res.data;
        this.toViewOriginPaper = true;
      }).catch((err) => {
        console.log(err);
      });
    },
    //一键阅卷，给所有考生评分
    gradeAll() {
      this.loading = true;
      Axios({
        method: 'post',
        url: '/admin/gradeAll',
        data: {
          exam_id: this.examDetail[this.curExamIndex].examId,
          adminToken: localStorage.getItem("adminToken")
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3 && (localStorage.getItem("adminToken") == null)) {
          this.$router.push({path: "/login"});
          return;
        }

        this.timer = setInterval(this.checkGradeProgress, 10000);

        // if(res.data <= 0){
        //     this.loading = false;
        //     this.$message({
        //         message: '一键阅卷完成',
        //         type: 'success'
        //     });
        //     this.viewExamDetail(this.curExamIndex);
        // }
      }).catch((err) => {
        this.$message({
          message: '一键阅卷失败',
          type: 'error'
        });
        console.log(err);
      });


    },
    //作弊检测,下载考生各个题目的时间差值
    gradeCheck(){
      this.loading = true;
      let url = this.getHostDomain() + '/check/'+this.examDetail[this.curExamIndex].examId;
      // console.log('-----'+url);
      var name =this.examDetail[this.curExamIndex].name+"-检测结果.xls";
      console.log("www",name);
      let a = document.createElement('a')
      a.href=url;
      a.setAttribute("download",name);
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      this.loading = false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSizeChange2(val) {
      this.stuPageSize = val;
    },
    handleCurrentChange2(val) {
      this.stuCurPage = val;
    },
    // 定位当前考试，设置添加考生的考试的当前索引
    locateCurExam(index) {
      this.curExamIndex = index;
      this.examTitle = this.examDetail[index].name;
      this.toAddExaminee = true;
    },
    //收卷
    take_up(index) {
      this.curExamIndex = index;
      if (this.examDetail[index].status === 1) {
        this.toViewExamDetail = false;
        this.setExamStatus(2, this.examDetail[index].examId);
        this.$notify({
          title: '成功',
          message: '收卷成功',
          type: 'success',
          duration: 3000
        });
      } else {
        this.$notify({
          title: '警告',
          message: '考试已结束，不能收卷！',
          type: 'warning',
          duration: 3000
        });
      }

      // Axios({
      //     method: 'post',
      //     url: '/admin/endExam',
      //     data: {
      //         exam_id: this.examDetail[index].examId,
      //         adminToken: localStorage.getItem("adminToken"),
      //     },
      //     transformRequest: [
      //         function (data) {
      //             let ret = '';
      //             for (let it in data) {
      //                 ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      //             }
      //             ret = ret.substring(0, ret.lastIndexOf('&'));
      //             return ret;
      //         }
      //     ],
      //     headers: {
      //         'Content-Type': 'application/x-www-form-urlencoded'
      //     },
      // }).then((res) => {
      //     if (res.data == 3) {
      //         this.$router.push({path: "/login"})
      //         return;
      //     }
      //     if (res.data == "success") {
      //         this.viewExamDetail(this.curExamIndex);
      //         this.examDetail[this.curExamIndex].status = 2;
      //     }
      // }).catch((err) => {
      //     console.log(err);
      // });
    },
    requestExaminee(index) {
      Axios({
        method: 'post',
        url: '/admin/getExaminee',
        data: {
          exam_id: this.examDetail[index].examId,
          adminToken: localStorage.getItem("adminToken"),
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        this.saveExaminee(res, index);
        // console.log(this.examDetail[index].examineeData)
      }).catch((err) => {
        console.log(err);
      })
    },
    // 查看考试详情
    viewExamDetail(index) {
      this.eidInput = '';
      this.curExamIndex = index;
      this.examTitle = this.examDetail[index].name;
      this.toViewExamDetail = true;
      this.examDetail[index].examineeData = [];
      this.stuCurPage = 1;
      this.requestExaminee(index);
    },
    // 创建考试
    createExam() {
      this.$refs['examForm'].validate((valid) => {
        if (valid) {
          Axios({
            method: 'post',
            url: '/admin/createExam',
            data: {
              adminToken: localStorage.getItem("adminToken"),
              exam_name: this.examForm.name,
              class_id: this.examForm.class,
              paper_id: this.examForm.paper,
              start_time: new Date(this.$moment(this.examForm.dateTime[0]).format('YYYY-MM-DD HH:mm:ss')).getTime(),
              end_time: new Date(this.$moment(this.examForm.dateTime[1]).format('YYYY-MM-DD HH:mm:ss')).getTime(),
              duration: this.examForm.duration,
              e_creator: this.examForm.creator,
            },
            transformRequest: [
              function (data) {
                let ret = '';
                for (let it in data) {
                  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret;
              }
            ],
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
          }).then((res) => {
            if (res.data == 3) {
              this.$router.push({path: "/login"})
              return;
            }
            if (res.data == 'success') {
              this.requestExam();
            }
          }).catch((err) => {
            console.log(err);
          })
          this.toCreateExam = false;

          this.$message({
            message: '考试创建成功！',
            type: 'success',
            duration: 3000
          });
        } else {
          return false;
        }
      });
    },
    // 添加考生
    addExaminee() {
      this.$refs['examineeForm'].validate((valid) => {
        if (valid) {
          this.toAddExaminee = false;
          let names = this.examineeForm.name.split(",");
          let ids = this.examineeForm.id.split(",");
          let IDcards = this.examineeForm.IDcard.split(",");
          let examinees = [];
          let error = [];
          if (names.length == ids.length && ids.length == IDcards.length) {
            for (let i = 0; i < names.length; i++) {
              if (names[i] == '' || ids[i] == '' || IDcards.length == '') {
                error.push(i + 1);
                continue;
              }
              let examinee = {};
              examinee.id = ids[i];
              examinee.name = names[i];
              examinee.IDcard = IDcards[i];
              examinees.push(examinee);
            }
          } else {
            this.$notify.error({
              title: '错误',
              message: '学生信息数量不一致',
              duration: 3000
            });
            return false;
          }
          // console.log(error);
          // console.log(examinees);
          Axios({
            method: 'post',
            url: '/admin/addExaminee',
            data: {
              adminToken: localStorage.getItem("adminToken"),
              exam_id: this.examDetail[this.curExamIndex].examId,
              class_id: this.examDetail[this.curExamIndex].classId,
              user_id: ids,
              user_name: names,
              user_IDcard: IDcards,
            },
            transformRequest: [
              function (data) {
                let ret = '';
                for (let it in data) {
                  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                }
                ret = ret.substring(0, ret.lastIndexOf('&'));
                return ret;
              }
            ],
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
          }).then((res) => {
            if (res.data == 3) {
              this.$router.push({path: "/login"})
              return;
            }
            // console.log(res);
          }).catch((err) => {
            console.log(err);
          })
          this.$notify({
            title: '暂未实现',
            message: '敬请期待',
            type: 'warning',
            duration: 3000
          });
        } else {
          return false;
        }
      });
    },
    // 开启考试
    startExam(index) {
      this.curExamIndex = index;
      // console.log("考试号：" + this.examDetail[index].examId);
      this.setExamStatus(1, this.examDetail[index].examId);
      this.$notify({
        title: '成功',
        message: '开启成功',
        type: 'success',
        duration: 3000
      });
    },
    // 结束考试
    endExam(index) {
      this.curExamIndex = index;
      // console.log("考试号：" + this.examDetail[index].examId);
      this.setExamStatus(2, this.examDetail[index].examId);
      this.$notify({
        title: '成功',
        message: '结束成功',
        type: 'success',
        duration: 3000
      });
    },
    // 删除考试
    deleteExam(index) {
      Axios({
        method: 'post',
        url: '/admin/deleteExam',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          exam_id: this.examDetail[index].examId,
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        this.toDelExam = false;
        if (res.data == "success") {
          this.$notify({
            title: '成功',
            message: this.examDetail[index].name + '，删除成功',
            type: 'success',
            duration: 3000
          });
        }
        this.requestExam();
      }).catch((err) => {
        console.log(err);
      });
    },
    // 删除考生
    deleteExaminee(index) {
      Axios({
        method: 'post',
        url: '/admin/deleteExaminee',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          exam_id: this.examDetail[this.curExamIndex].examId,
          user_id: this.examDetail[this.curExamIndex].examineeData[index].id,
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        // console.log(res);
      }).catch((err) => {
        console.log(err);
      })
      this.examDetail[this.curExamIndex].examineeData.splice(index, 1);
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 3000
      });
    },
    //评阅本场考试中所有提交代码的考生的试卷
    reviewPapers(scope) {
      this.curExamIndex = (this.currentPage - 1) * this.pageSize + scope.$index;
      this.examPapers = [];
      this.curPaper = 0;
      Axios({
        method: 'post',
        url: '/admin/getExamPapers',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          exam_id: scope.row.examId
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data === 3) {
          this.$router.push({path: "/login"})
          return;
        }
        if (res.data.length === 0) {
          this.setExamStatus(4, scope.row.examId);
          this.$notify({
            title: '成功',
            message: '所有评分已经完成！',
            type: 'success',
            duration: 3000
          });
          return;
        }
        this.examPapers = res.data;
        // for (let i = 0; i < this.examPapers.length; i++) {
        //     for (let j = 0; j < this.examPapers[i].length; j++) {
        //         if( this.examPapers[i][j].answer != null)
        //             this.examPapers[i][j].answer = this.examPapers[i][j].answer.replace(/\n/g, "<br>").replace(/\s/g, "&nbsp;");
        //     }
        // }
        this.setExamStatus(3, scope.row.examId);
        // console.log(res);
        // console.log(this.examPapers);
        // console.log(this.curPaper);
        this.toReviewPapers = true;
      }).catch((err) => {
        console.log(err);
      });
    },
    //设置考试状态
    setExamStatus(status, examId) {
      Axios({
        method: 'post',
        url: '/admin/setExamStatus',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          exam_status: status,
          exam_id: examId
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data === 3) {
          this.$router.push({path: "/login"})
          return;
        }
        if (res.data === "success") {
          this.requestExam();
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    // 查阅考生试卷
    reviewStuPaper(index) {
      this.curStuIndex = index;
      Axios({
        method: 'post',
        url: '/admin/searchExamDetail',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          examinee_id: this.examDetail[this.curExamIndex].examineeData[this.curStuIndex].id,
          exam_id: this.examDetail[this.curExamIndex].examId,
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        this.stuPaper = [];
        // console.log(res);
        for (let i = 0; i < res.data.length; i++) {
          let stuPapers = {};
          stuPapers.problem_id = res.data[i].problem_id;
          stuPapers.problem_description = this.handleProblemDescription(res.data[i].problem_description);
          stuPapers.problem_input_format = res.data[i].problem_input_format;
          stuPapers.problem_sample_input = res.data[i].problem_sample_input;
          stuPapers.problem_output_format = res.data[i].problem_output_format;
          stuPapers.problem_sample_output = res.data[i].problem_sample_output;
          stuPapers.score = res.data[i].score == null ? 0 : res.data[i].score;
          stuPapers.submit_ip = res.data[i].submit_ip;
          stuPapers.submit_time = this.getTime(res.data[i].submit_time);
          stuPapers.language = res.data[i].language;
          stuPapers.answer = res.data[i].answer;
          // if(res.data[i].answer != null)
          //     stuPapers.answer = res.data[i].answer.replace(/\n/g, "<br>").replace(/\s/g, "&nbsp;");
          this.stuPaper.push(stuPapers);
          this.toReviewStuPaper = true;
        }
      }).catch((err) => {
        console.log(err);
      });
    },
    //创建考试中读取班级选项卡
    requestClass() {
      this.classOptions = [];
      Axios({
        method: 'post',
        url: '/admin/getClassOptions',
        data: {
          adminToken: localStorage.getItem("adminToken"),
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        for (let i = 0; i < res.data.length; i++) {
          let option = {};
          option.key = res.data[i].class_id;
          option.value = res.data[i].class_name;
          this.classOptions.push(option);
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    //创建考试中读取试卷选项卡
    requestPaper() {
      this.paperOptions = [];
      Axios({
        method: 'post',
        url: '/admin/getPaperOptions',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          adminName: localStorage.getItem("adminName"),
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        for (let i = 0; i < res.data.length; i++) {
          let option = {};
          option.key = res.data[i].paper_id;
          option.value = res.data[i].paper_title;
          this.paperOptions.push(option);
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    //搜索考试
    searchExam() {
      Axios({
        method: 'post',
        url: '/admin/searchExam',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          exam_name: this.examInput,
          exam_status: this.examDetail[0].status,
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        this.currentPage = 1;
        // console.log(res);
        this.saveExam(res);
      }).catch((err) => {
        console.log(err);
      })
    },
    //搜索考生
    searchExaminee(index) {
      Axios({
        method: 'post',
        url: '/admin/searchExaminee',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          examinee_name: this.eidInput,
          exam_id: this.examDetail[index].examId,
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        // console.log(res);
        this.examDetail[index].examineeData = [];
        this.stuCurPage = 1;
        this.saveExaminee(res, index);
        // console.log(this.examDetail[index].examineeData);
      }).catch((err) => {
        console.log(err);
      })
    },
    //修改分数，reviewAll 表示是否评阅全部，0 否 1 是
    uploadScore(paper, userId, reviewAll) {
      let scores = [];
      let problems = [];
      for (let i = 0; i < paper.length; i++) {
        if (paper[i].answer != null) {
          problems.push(paper[i].problem_id);
          scores.push(paper[i].score);
        }
      }
      // console.log(problems);
      // console.log(scores);
      // console.log(userId)

      Axios({
        method: 'post',
        url: '/admin/uploadScore',
        data: {
          adminToken: localStorage.getItem("adminToken"),
          problems: problems,
          scores: scores,
          user_id: userId,
          exam_id: this.examDetail[this.curExamIndex].examId,
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        }
        // console.log(res);
        if (res.data == "success") {
          if (reviewAll === 1) {
            ++this.curPaper;
            if (this.curPaper < this.examPapers.length) {
              this.$notify({
                title: '评分成功',
                message: '为您跳转下一张答卷！',
                type: 'success',
                duration: 3000
              });
            } else {
              this.setExamStatus(4, this.examDetail[this.curExamIndex].examId);
              this.toReviewPapers = false;
              this.$notify({
                title: '成功',
                message: '所有评分已经完成！',
                type: 'success',
                duration: 3000
              });
            }
          } else if (reviewAll === 0) {
            this.$notify({
              title: '成功',
              message: '评分成功！',
              type: 'success',
              duration: 3000
            });
            this.toReviewStuPaper = false;
            this.viewExamDetail(this.curExamIndex);
          }
        }
      }).catch((err) => {
        console.log(err);
      })
    },
    //导出成绩成Excel
    exportExcel() {
      var xlsxParam = {raw: true};//转换成excel时，使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#exportTable"), xlsxParam);
      // var wb = XLSX.utils.json_to_sheet(this.examDetail[this.curExamIndex].examineeData)
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
            new Blob([wbout], {type: "application/octet-stream;charset=utf-8"}),
            this.examDetail[this.curExamIndex].name + '.xlsx'
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    downloadExcel() {
      // console.log("downloadExcel");
      let downloadUrl = '';
      // if(this.ip == '127.0.0.1')
      //     downloadUrl = "http://prog.myxls.cn/api/admin/userExcel?exam_id=" + this.examDetail[this.curExamIndex].examId + "&exam_name=" + this.examDetail[this.curExamIndex].name + "&adminToken=" + localStorage.getItem("adminToken");
      // else
      //     downloadUrl = process.env.VUE_APP_URL + "/admin/userExcel?exam_id=" + this.examDetail[this.curExamIndex].examId + "&exam_name=" + this.examDetail[this.curExamIndex].name + "&adminToken=" + localStorage.getItem("adminToken");
      downloadUrl = process.env.VUE_APP_URL + "/admin/userExcel?exam_id=" + this.examDetail[this.curExamIndex].examId + "&exam_name=" + this.examDetail[this.curExamIndex].name + "&adminToken=" + localStorage.getItem("adminToken");
      let a = document.createElement("a");
      a.href = downloadUrl;
      a.download = downloadUrl;
      a.click();
      return false;
    },
    //查重报告，下载重复率检测报告
    downloadRepCheckReport() {
      let downloadUrl = '';
      // if(this.ip == '127.0.0.1')
      //     downloadUrl = "http://prog.myxls.cn/api/admin/downloadRepCheckReport?exam_id="
      //         + this.examDetail[this.curExamIndex].examId + "&exam_name="
      //         + this.examDetail[this.curExamIndex].name + "&adminToken="
      //         + localStorage.getItem("adminToken");
      // else
      //     downloadUrl = process.env.VUE_APP_URL + "/admin/downloadRepCheckReport?exam_id="
      //         + this.examDetail[this.curExamIndex].examId + "&exam_name="
      //         + this.examDetail[this.curExamIndex].name + "&adminToken="
      //         + localStorage.getItem("adminToken");
      downloadUrl = process.env.VUE_APP_URL + "/admin/downloadRepCheckReport?exam_id="
          + this.examDetail[this.curExamIndex].examId + "&exam_name="
          + this.examDetail[this.curExamIndex].name + "&adminToken="
          + localStorage.getItem("adminToken");
      let a = document.createElement("a");
      a.href = downloadUrl;
      a.download = downloadUrl;
      a.click();
      return false;
    },
    downloadZip() {
      console.log("downloadZip");
      let downloadUrl = '';
      // if(this.ip == '127.0.0.1')
      //     downloadUrl = "http://prog.myxls.cn/api/admin/zipFile?exam_id=" + this.examDetail[this.curExamIndex].examId + "&exam_name=" + this.examDetail[this.curExamIndex].name + "&adminToken=" + localStorage.getItem("adminToken");
      // else
      //     downloadUrl = process.env.VUE_APP_URL + "/admin/zipFile?exam_id=" + this.examDetail[this.curExamIndex].examId + "&exam_name=" + this.examDetail[this.curExamIndex].name + "&adminToken=" + localStorage.getItem("adminToken");
      downloadUrl = process.env.VUE_APP_URL + "/admin/zipFile?exam_id=" + this.examDetail[this.curExamIndex].examId + "&exam_name=" + this.examDetail[this.curExamIndex].name + "&adminToken=" + localStorage.getItem("adminToken");
      let a = document.createElement("a");
      a.href = downloadUrl;
      a.download = downloadUrl;
      a.click();
      return false;
    },
    //处理题目的显示：换行、图片
    handleProblemDescription(description) {
      //处理换行
      description = description.replace(/\n/g, "<br>");
      //处理图片
      let temp = description;
      let picIndex = temp.indexOf('[1]:');
      if (picIndex != -1) {
        let picAddress = [];
        picAddress = temp.substring(picIndex).replace('<br>', ',').replace(new RegExp(/( )/g), "").split(',');
        for (let i = 0; i < picAddress.length; i++) {
          picAddress[i] = "<img src='" + picAddress[i].substring(4) + "'>";
        }
        description = description.substring(0, picIndex);
        for (let i = 0; i < picAddress.length; i++) {
          let pic = description.indexOf('![enter image description here]');
          let head = description.substring(0, pic);
          let tail = description.substring(pic + 34, description.length);
          description = head + picAddress[i] + tail;
        }
      }
      return description;
    },
    //根据每个题目的得分计算总分
    computeTotalScore(paper) {
      let totalScore = 0;
      for (let i = 0; i < paper.length; i++) {
        totalScore += paper[i].score;
      }
      return totalScore;
    },
    //定时器，定时访问后台是否处理完成
    checkGradeProgress() {
      Axios({
        method: 'post',
        url: '/admin/checkGradeProgress',
        data: {
          exam_id: this.examDetail[this.curExamIndex].examId,
          adminToken: localStorage.getItem("adminToken")
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        if (res.data == 3) {
          this.$router.push({path: "/login"})
          return;
        } else if (res.data == 1000001) {
          clearInterval(this.timer);
          this.loading = false;
          this.viewExamDetail(this.curExamIndex);
          this.$message.error("评测机发生内部错误，请联系管理员");
        } else if (res.data <= 0) {
          clearInterval(this.timer);
          this.loading = false;
          this.viewExamDetail(this.curExamIndex);
          this.$message({
            message: '一键阅卷完成',
            type: 'success'
          });
        }
      }).catch((err) => {
        this.$message({
          message: '一键阅卷遇到了错误',
          type: 'error'
        });
        console.log(err);
      })
    },
    checkIp() {
      Axios({
        method: 'post',
        url: '/admin/checkIp',
        data: {
          adminToken: localStorage.getItem("adminToken")
        },
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'));
            return ret;
          }
        ],
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
      }).then((res) => {
        console.log(res.data);
        this.ip = res.data;
      }).catch((err) => {
        console.log(err);
      })
    }


  },
  beforeDestroy() {
    clearInterval(this.timer);
  }

}

</script>

<style scoped>
.exam {
  width: 100%;
}

.filter-container {
  padding-bottom: 10px;
}

.filter-item {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.item-input {
  width: 200px;
  margin-right: 5px;
}

.filter-container .filter-item:nth-child(3), .filter-container .filter-item:nth-child(4) {
  margin-left: 16px;
}

.exam-list {
  width: 100%;
}

.pagination-container {
  margin-top: 30px;
}

.exam-list .col2-cell-style {
  color: #409EFF;
  cursor: pointer;
}

.filter-bar {
  width: 100%;
  padding-bottom: 10px;
}

.filter-bar .el-input {
  width: 200px;
  margin-right: 5px;
}

.filter-bar .item-margin-left-16 {
  margin-left: 16px;
}

.el-dialog .el-table .col2-cell-style {
  color: #409EFF;
  cursor: pointer;
}

.el-dialog .stu-paper-container {
  margin: 0 20px;
}

.el-dialog .stu-paper-container h1 {
  text-align: center;
  font-size: 2.5em;
}

.el-dialog .stu-paper-container h3 {
  text-align: left;
}

.el-dialog .stu-paper-container .el-row {
  margin-bottom: 30px;
}

.el-dialog .stu-paper-container .stu-answer {
  margin-left: 20px;
}

.el-dialog .stu-paper-container .stu-paper-footer {
  text-align: right;
  margin-top: 30px;
}

.el-dialog .paper-container {
  margin: 0 20px;
}

.el-dialog .paper-container .paper-header h1 {
  text-align: center;
  font-size: 2.5em;
}

.el-dialog .paper-container .paper-info {
  text-align: center;
  padding: 20px;
}

.el-dialog .paper-container .paper-info h3 {
  display: inline-block;
  width: 25%;
}

.paper-container .paper-content {
  padding: 20px;
}

.filter-bar .el-progress {
  margin-left: 20px;
}

</style>
